package com.devunion.reader.server;

import com.devunion.bogdan.model.project.RelativePathConverter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Timoshenko Alexander 29.01.2009 : 16:18:13
 */
public class LoadImageController
        implements Controller {
    private RelativePathConverter relativePathConverter;

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        String path = httpServletRequest.getParameter("path");
        String pname = httpServletRequest.getParameter("pname");

        if (StringUtils.isBlank(path) || StringUtils.isBlank(pname)) {
            return null;
        }

        File fileToLoad = new File(relativePathConverter.getAbsolutePath(pname, path));

        if (!fileToLoad.exists() || fileToLoad.isDirectory()) {
            return null;
        }

        InputStream inputStream = new FileInputStream(fileToLoad);
        OutputStream outputStream = httpServletResponse.getOutputStream();

        int bytesRead = 0;
        byte[] buffer = new byte[8192];

        try {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }

        return null;
    }

    public void setRelativePathConverter(RelativePathConverter relativePathConverter) {
        this.relativePathConverter = relativePathConverter;
    }
}
